﻿// это код взят из mvc2-preview2-sources

using System;
using System.Collections.Generic;
using System.Threading;

namespace Basmus.Util
{
    public class ReaderWriterCache<TKey, TValue>
    {
        private readonly Dictionary<TKey, TValue> _cache;
        private readonly ReaderWriterLock _rwLock = new ReaderWriterLock();

        public ReaderWriterCache()
            : this(null)
        {
        }

        public ReaderWriterCache(IEqualityComparer<TKey> comparer)
        {
            _cache = new Dictionary<TKey, TValue>(comparer);
        }

        protected Dictionary<TKey, TValue> Cache
        {
            get
            {
                return _cache;
            }
        }

        public TValue FetchOrCreateItem(TKey key, Func<TValue> creator)
        {
            // first, see if the item already exists in the cache
            _rwLock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                TValue existingEntry;
                if (_cache.TryGetValue(key, out existingEntry))
                {
                    return existingEntry;
                }
            }
            finally
            {
                _rwLock.ReleaseReaderLock();
            }

            // insert the new item into the cache
            TValue newEntry = creator();
            _rwLock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                TValue existingEntry;
                if (_cache.TryGetValue(key, out existingEntry))
                {
                    // another thread already inserted an item, so use that one
                    return existingEntry;
                }

                _cache[key] = newEntry;
                return newEntry;
            }
            finally
            {
                _rwLock.ReleaseWriterLock();
            }
        }

    }
}

